#include "MyISP.h" 
#include <algorithm>
#include <math.h>

void GC(ImageRGB& rgb, int bw)
{
    float maxval = pow(2, bw) - 1;

    int histogram[256] = { 0 };
    for (int y = 0; y < rgb.getHeight(); y++)
    {
        for (int x = 0; x < rgb.getWidth(); x++)
        {
            int gray = (rgb.at(y, x).R + rgb.at(y, x).G + rgb.at(y, x).B) / 3;
            gray = std::min(255, std::max(0, gray));
            histogram[gray]++;
        }
    }

    
    int cumulativeHistogram[256] = { 0 };
    cumulativeHistogram[0] = histogram[0];
    for (int i = 1; i < 256; i++)
    {
        cumulativeHistogram[i] = cumulativeHistogram[i - 1] + histogram[i];
    }

    int totalPixels = rgb.getHeight() * rgb.getWidth();
    float map[256];
    for (int i = 0; i < 256; i++)
    {
        map[i] = (float)(cumulativeHistogram[i]) / totalPixels * 255;
    }

    for (int y = 0; y < rgb.getHeight(); y++)
    {
        for (int x = 0; x < rgb.getWidth(); x++)
        {
            int gray = (rgb.at(y, x).R + rgb.at(y, x).G + rgb.at(y, x).B) / 3;
            gray = std::min(255, std::max(0, gray));
            int newGray = map[gray];
            rgb.at(y, x).R = rgb.at(y, x).G = rgb.at(y, x).B = newGray;
        }
    }
}
